package config

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/spf13/viper"
)

var rootPath, procName = GetRootPath()

func NewConfig(file string) *viper.Viper {
	if file == "" {
		file = fmt.Sprintf("configs/%s.toml", procName)
	}
	var confType string
	confExt := strings.TrimLeft(filepath.Ext(file), ".")
	switch confExt {
	case "yaml", "yml":
		confType = "yaml"
	case "toml", "conf":
		confType = "toml"
	case "json":
		confType = "json"
	case "ini":
		confType = "ini"
	case "hcl", "tfvars":
		confType = "hcl"
	case "properties", "props", "prop":
		confType = "properties"
	case "dotenv", "env":
		confType = "env"
	default:
		panic(fmt.Sprintf("不支持的配置文件类型: %s", confExt))
	}
	conf := viper.New()
	conf.SetConfigName(file)
	conf.SetConfigType(confType)
	conf.AddConfigPath(rootPath)
	conf.AddConfigPath(".")
	conf.AddConfigPath("/")

	err := conf.ReadInConfig()
	if err != nil {
		panic(err)
	}
	return conf
}

// GetRootPath 获取程序根目录
func GetRootPath() (string, string) {
	proc, err := exec.LookPath(os.Args[0])
	if err != nil {
		panic(fmt.Sprintf("获取程序名失败。err: %v\n", err))
	}

	proc, err = filepath.Abs(proc)
	if err != nil {
		panic(fmt.Sprintf("获取程序路径失败。err: %v\n", err))
	}

	return filepath.Dir(proc), filepath.Base(proc)
}
